package httprequest

import (
	"gitee.com/liukexing/mqbroker/core/driver/component"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/server/pubsub"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"time"
)

func GetTaskInfo() map[string]typedef.TaskInfo {
	TaskBootStrap()
	return map[string]typedef.TaskInfo{
		"FindRegister::@every 1m": typedef.TaskInfo{
			Name:   "注册节点查询",
			Handle: FindRegisterTask,
			Arg:    nil,
		},
		"ComReg::@every 2m": typedef.TaskInfo{
			Name:   "模块注册",
			Handle: ComRegTask,
			Arg:    nil,
		},
		"UpConfig::@every 30s": typedef.TaskInfo{
			Name:   "上传配置",
			Handle: UpConfigTask,
			Arg:    nil,
		},
		//"GetConfig::@every 30s": typedef.TaskInfo{
		//	Name:   "获取配置",
		//	Handle: GetConfigTask,
		//	Arg:    nil,
		//},
	}
}


/*
time.Sleep(time.Second)
		logger.Info(typedef.CommInfo{
			Info:Config.Info,
			Message:"Start ComRegTask UpConfig",
		})
		pubsub.CommandMsgPub(Config.Info.ID, sender,"UpConfig", map[string]interface{}{"Component":"core.server.http","Msgflow":Config.Info.ID,"Config": Config.Info})
*/
//初始化
func TaskBootStrap() {
	go func() {
		time.Sleep(time.Second)
		FindRegisterTask(nil)
		time.Sleep(time.Second)
		FindRegisterTask(nil)
	}()

}

//注册节点查询
func FindRegisterTask(arg map[string]interface{}) error {
	if reqid, err := component.FindRegister(Config.Info); !err {
		ReqMap.Store(reqid, typedef.MsgReceiver{Handle: "FindRegister", Stamp: time.Now(), Mutex: true, TimeOut: time.Minute})
	}
	return nil
}

//模块注册
func ComRegTask(arg map[string]interface{}) error {
	if time.Now().Sub(LastTick) > time.Minute*2 {
		FindMap.Range(func(key, value interface{}) bool {
			pubsub.CommandMsgPub(Config.Info.ID, key.(string), "Register", map[string]interface{}{"info": Config.Info})
			return false
		})
	}
	return nil
}

//获取配置
func UpConfigTask(arg map[string]interface{}) error {
	FindMap.Range(func(key, value interface{}) bool {
		logger.Info(typedef.CommInfo{
			Info:Config.Info,
			Message:"Start ComRegTask UpConfig",
		})
		pubsub.CommandMsgPub(Config.Info.ID, key.(string),"UpConfig", map[string]interface{}{"Component":"core.server.http","Msgflow":Config.Info.ID,"Config": Config.Info})
		return false
	})
	return nil
}

//获取配置
func GetConfigTask(arg map[string]interface{}) error {
	FindMap.Range(func(key, value interface{}) bool {
		resp := pubsub.MessageReplyClient(key.(string),"GetConfig",map[string]interface{}{"module":Config.Info.Module},20)
		if resp.Error {
			return true
		}
		c := make(map[string]interface{})
		err := typedef.Decode(resp.Data,&c)
		if err != nil {
			return  true
		}
		return false
	})
	return nil
}
